﻿using System;

namespace YJKGridTopologyCal.Utilities
{
	internal static class BitTweaks
	{
		internal static short ReverseByteOrder(short value)
		{
			return (short)BitTweaks.ReverseByteOrder((ushort)value);
		}

		internal static int ReverseByteOrder(int value)
		{
			return (int)BitTweaks.ReverseByteOrder((uint)value);
		}

		internal static long ReverseByteOrder(long value)
		{
			return (long)BitTweaks.ReverseByteOrder((ulong)value);
		}

		internal static float ReverseByteOrder(float value)
		{
			byte[] bytes = System.BitConverter.GetBytes(value);
			Array.Reverse(bytes, 0, 4);
            return System.BitConverter.ToSingle(bytes, 0);
		}

		internal static double ReverseByteOrder(double value)
		{
			return BitConverter.Int64BitsToDouble(BitTweaks.ReverseByteOrder(BitConverter.DoubleToInt64Bits(value)));
		}

		internal static ushort ReverseByteOrder(ushort value)
		{
			return (ushort)((int)(value & 255) << 8 | (value & 65280) >> 8);
		}

		internal static uint ReverseByteOrder(uint value)
		{
			return (value & 255u) << 24 | (value & 65280u) << 8 | (value & 16711680u) >> 8 | (value & 4278190080u) >> 24;
		}

		internal static ulong ReverseByteOrder(ulong value)
		{
            //long aa = unchecked(-16777216);
            //ulong ss = ulong(aa);
            return (value & 255UL) << 56 | (value & 65280UL) << 40 | (value & 16711680UL) << 24 | (value & 4278190080u) << 8 | (value & 1095216660480UL) >> 8 | (value & 280375465082880UL) >> 24 | (value & 71776119061217280UL) >> 40 | (value & 18374686479671623680UL) >> 56;
		}
	}
}
